<template>
  <!--    面包屑-->
  <el-breadcrumb separator-class="el-icon-arrow-right">
    <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
    <el-breadcrumb-item>权限管理</el-breadcrumb-item>
    <el-breadcrumb-item>角色列表</el-breadcrumb-item>
  </el-breadcrumb>
  <!--    卡片区域-->
  <el-card class="box-card">
    <el-button type="primary" @click="addUserVisible=true">添加角色</el-button>
    <!--      表格,border加边框，stripe加隔行变色,:data="userList"数据在这里-->
    <el-table
      border
      stripe
      :data="tableData"
      style="width: 100%"
      max-height="650"
    >
<!--      带右箭头这列，点击可以展开信息 type="expand"-->
      <el-table-column type="expand">
        <template v-slot="roleChildren">
<!--渲染一级菜单:class="['b_bottom',i===0?'b_top':'','vcenter']，加下边框，如果是第一个加上边框，垂直居中
roleChildren.row.children一级的名字，
-->
          <el-row :class="['b_bottom',i===0?'b_top':'','vcenter']" v-for="(item_1,i) in roleChildren.row.children" :key="item_1.id" >
            <!--  <el-col  :span="5" >第一列占24分之5-->
            <el-col  :span="5" >
<!--              每个便签的名字item_1.authName-->
              <el-tag type="primary">{{item_1.authName}}</el-tag>
              <i class="el-icon-caret-right"></i>
            </el-col>
<!--            剩下的还有24-5=19，里面分为两列-->
            <el-col  :span="19" >
              <!--              渲染二级菜单-->
              <el-row :class="[i2===0?'':'b_top','vcenter']" v-for="(item_2,i2) in item_1.children" :key="item_2.id" @click="a(item_2.id)">
                <el-col  :span="6" >
                  <el-tag type="success">{{item_2.authName}}</el-tag>
                  <i class="el-icon-caret-right"></i>
                </el-col>
<!--               注意！！！el-row是24，所以里面要看成24，分为6和18-->
                <el-col  :span="18" >
                  <el-tag type="warning" closable v-for="item_3 in item_2.children" :key="item_3.id"   @close="closeBtn(item_3.id,roleChildren.row.id)">{{item_3.authName}}<i></i></el-tag>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </template>
      </el-table-column>
      <el-table-column
       type="index"
        label="#">
      </el-table-column>
      <el-table-column
        prop="roleName"
        label="角色名称">
      </el-table-column>
      <el-table-column
        prop="roleDesc"
        label="角色描述">
      </el-table-column>
      <el-table-column
        prop="level"
        label="操作">
        <template v-slot="mySlot">
          <el-tooltip class="item" effect="dark" content="编辑" placement="top-start" >
            <el-button type="primary" icon="el-icon-search" @click="editDialog(mySlot.row.id)">编辑</el-button>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="删除" placement="top-start">
            <el-button type="danger" icon="el-icon-delete-solid"  @click="delDialog(mySlot.row)">删除</el-button>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="分配权限" placement="top-start">
            <el-button type="warning"  icon="el-icon-setting" @click="treeDialog(mySlot.row)">分配权限</el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <!--点击添加用户弹出的表单-->
    <el-dialog title="添加用户" v-model="addUserVisible" width="50%" >
      <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="80px" class="demo-ruleForm">
        <el-form-item label="角色名称" prop="roleName">
          <el-input  v-model="ruleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input  v-model="ruleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <template #footer >
          <span class="dialog-footer" >
            <el-button @click="resetForm('ruleForm')">取 消</el-button>
            <el-button type="primary" @click="add('ruleForm')">确 定</el-button>
          </span>
      </template>
    </el-dialog>

    <!--      编辑按钮的弹出框-->
    <el-dialog title="编辑" v-model="editDialogVisible" width="50%">
      <el-form :model="updateForm"  status-icon :rules="rules" ref="updateForm" label-width="80px" class="demo-ruleForm">
        <el-form-item label="角色名称" prop="roleName" >
          <el-input  v-model="updateForm.roleName" ></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input  v-model="updateForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
           <span  class="dialog-footer">
            <el-button @click="editDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="edit()">确 定</el-button>
          </span>
      </template>
    </el-dialog>

    <!--      删除按钮的弹出框-->
    <el-dialog
      title="提示"
      v-model="delDialogVisible"
      width="50%"
      center>
      <span>您确定要删除  {{userName}} 角色吗？</span>
      <template #footer>
           <span  class="dialog-footer">
            <el-button @click="delDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="del">确 定</el-button>
          </span>
      </template>
    </el-dialog>

<!--    分配权限的弹出框
 -->
    <el-dialog
    title="分配权限"
    v-model="showTreeDialog"
    width="30%"
    :before-close="handleClose">
<!--      树  default-expand-all默认展开所有， :data="rolesList"所有数据
  node-key="id"  :default-checked-keys="checkArr" 这两个要一起用，默认选中的key是checkAll变量
   :props="treeProps"必须有这个


      -->
      <el-tree
      :data="rolesList"
      :props="treeProps"
      show-checkbox
      node-key="id"
      :default-checked-keys="checkArr"
      default-expand-all
      ref="treeRef"
      >
      </el-tree>
      <template #footer>
          <span class="dialog-footer">
            <el-button @click="showTreeDialog= false">取消</el-button>
            <el-button type="primary" @click="setRoleInfo">确定</el-button>
          </span>
      </template>
    </el-dialog>
  </el-card>
</template>

<script>
import {ElMessage} from "element-plus";

export default {
  name: "roles",
  data(){
    return{
      rolesList:[],
      tableData:[],
      addUserVisible:false,
      editDialogVisible:false,
      delDialogVisible:false,
      showTreeDialog:false,
      checkArr:[],
      userId:0,
      username:'',
      ruleForm: {
        roleName: '',
        roleDesc: ''
      },
      updateForm:{

      },
      rules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }
        ]
      },
      treeProps:{
        label:'authName',//意思是树节点的内容就是authName
        children:'children'//子节点名字
      },
      role_id:0
    }
  },
  created() {
    this.getAllRoles();
  },
  methods:{
    getAllRoles(){
      this.axios.get('roles').then(resp=>{
        if(resp.data.meta.status!==200) return;
        this.tableData=resp.data.data;
      }).catch(err=>{
        console.log(err);
      })
    },
    editDialog(id){
      console.log(id);
      this.editDialogVisible=true;
      this.userId=id;
      this.axios.get(`roles/${this.userId}`,{
        params: this.userId
      }).then(resp=>{
        this.updateForm=resp.data.data;//将编辑弹出的对话框加上原有的内容
        console.log(resp);
      }).catch(err=>{
        console.log(err);
      })
    },
    edit(){
      this.axios.put(`roles/${this.userId}`,{
        roleName:this.updateForm.roleName,
        roleDesc:this.updateForm.roleDesc
      }).then(resp=>{
        if (resp.data.meta.status !== 200) return ElMessage.error(data.data.meta.msg);
        ElMessage.success("修改成功");
        this.editDialogVisible=false;
        this.getAllRoles();
      }).catch(err=>{
        console.log(err);
      })
    },
    //删除
    delDialog(row) {
      console.log(row);
      this.userId=row.id;//点击删除，传过来了此行的id,放到userId里面存，其他的使用userId就行
      this.userName=row.roleName;
      this.delDialogVisible=true;

    },
    del(){
      this.axios.delete(`roles/${this.userId}`).then(resp=>{
        console.log(resp);
        if(resp.data.meta.status!==200) return ElMessage.error("删除失败");
        ElMessage.success("删除成功");
        this.delDialogVisible=false;
        //重新刷新用户列表
        this.getAllRoles();
      }).catch(err=>{
        console.log(err);
      })
    },
    //弹出框点击×
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.addUserVisible = false;
    },
    add(formName){//添加用户点击事件
      this.axios.post('roles',this.ruleForm).then(resp=>{
        console.log(resp);
        this.getAllRoles();
        // this.addUserVisible = false;
        this.resetForm(formName);
      }).catch(err=>{
        console.log(err);
      })
    },
    treeDialog(row){//点击分配权限，获取到数值resp,给roleList
      this.role_id=row.id;
      this.axios.get('rights/tree').then(resp=>{
        if(resp.data.meta.status!==200) return ElMessage.error('获取角色列表错误');
        this.rolesList=resp.data.data;
      }).catch(err=>{
        console.log(err);
      });
      this.getNodeById(row);//得到选中
      this.showTreeDialog=true;//取消按钮
    },
    getNodeById(node){
      if(!node.children){//如果他节点为空
        return this.checkArr.push(node.id);//把id放到checkArr中
      }
      node.children.forEach(item=>{//子节点不为空
        this.getNodeById(item);
      })
    }
    ,
    setRoleInfo(){//点击确定,后给选定的添加权限
      //这里用到了ref，叫treeRef。
      //得到选定的和半选定的复选框，放到keys里面，...是es6新语法
      let keys=[
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ];
      let keyStr=keys.join(',');//文档要求数据以逗号分隔
      console.log(keyStr);
      this.axios.post(`roles/${this.role_id}/rights`,{
        rids:keyStr
      }).then(resp=>{
        if(resp.data.meta.status!==200) return  ElMessage.error('授权失败');
        ElMessage.success('更新成功');
        this.showTreeDialog=false;
        this.getAllRoles();
      }).catch(err=>{
        console.log(err);
      })
    },
    handleClose(){
      this.checkArr=[];//清空数组，不然点击其他的弹出的对话框就是点击第一个的数据
      this.showTreeDialog=false;
    },
    closeBtn(rightId,roleId){//roleId是点×的元素
      console.log(rightId);
      this.axios.delete(`roles/${roleId}/rights/${rightId}`).then(resp=>{
        this.getAllRoles();
      }).catch(err=>{
        console.log(err);
      })
    },
    a(id){
      console.log("a:"+id);
    }

  }
}
</script>

<style scoped>
.el-breadcrumb{
  font-size: 20px;

}
.box-card{
  margin-top: 20px;
}
.el-table{
  margin-top: 20px;
}

.b_bottom {
  border-bottom: 1px solid #eee;
}
.b_top{
  border-top: 1px solid #eee;
}
/*垂直居中*/
.vcenter{
  display: flex;
  align-items: center;
}
/*所有的el-tag元素10px*/
.el-tag{
  margin: 10px;
}
</style>
